<?php
namespace app\home\controller;

use Qcloud\Sms\SmsMultiSender;
use think\Controller;
use think\Db;
use think\Request;

class Sendmessage extends Controller{

    // 短信应用SDK AppID
    public $appid = 1400576972;

    // 短信应用SDK AppKey
    public $appkey = "a699bc79e26650c3f140588900e4d362";

    // 短信模板ID，需要在短信应用中申请
    public $templateId = 1148005;

    // 签名
    public $smsSign = "忆流年";



    /**发送邮件
     * @param array $phoneNumbers 号码的集合
     * @param array $data 数据的集合（根据模板）
     * @return string 发送结果
     */
    private function sendMessage($phoneNumbers=[],$data=[])
    {
        try {
            //实例化发件库
            $msender = new SmsMultiSender($this->appid, $this->appkey);

            //执行发送并返回结果
            return $msender->sendWithParam("86", $phoneNumbers,$this->templateId, $data, $this->smsSign, "", "");

        } catch(\Exception $e) {
            return $e->getMessage();
        }
    }

    /** 获取excel中内容并转化成数组
     * @param $file string 文件地址
     * @param $from_row  int 从第几行开始导入
     * @param $from_col int 从第几列开始导入
     * @param $to_col int 导出到第几行
     * @return array
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    function excel_to_array($file,$from_row,$from_col,$to_col)   //将excel中的数据转换成数组
    {
        $file_type='xlsx';
        if($file_type=='xlsx'){
            $reader = \PHPExcel_IOFactory::createReader('Excel2007');
        }else{
            $reader=\PHPExcel_IOFactory::createReader('Excel5');
        }

        $excel = $reader->load($file,$encode = 'utf-8');
        //读取第一张表
        $sheet = $excel->getSheet(0);
        //获取总行数
        $row_num = $sheet->getHighestRow();
        $col_num=$to_col;

        //获取总列数
        $row=0;
        $data = array(); //数组形式获取表格数据$
        for ($i = $from_row; $i <= (int)$row_num; $i ++) {
            $col=0;
            for($j=$from_col-1;$j<=(int)$col_num-1;$j++){
                $data[$row][$col]  = $sheet->getCellByColumnAndRow($j,$i)->getValue();
                $col++;
            }
            $row++;
        }
        return $data;
    }

    public function doSend()
    {
        //获取发送的用户的数据
        $users=explode(",",input('get.users'));

        var_dump($users);
    }

    public function send()
    {
        $SafeCode=cookie('SafeCode');
        $UserData=Db::name('users')->field('password',true)->where('SafeCode',$SafeCode)->find();
        if($UserData['auth']!=3){
            return "无权操作";
        }else{
            return $this->fetch('sendMessage/send');
        }

    }


    public function SendAll()   //批量发送邮件
    {
        $users=[];
        $re=new Request();
        $files=$re->file('file');
        if($files){
            $info=$files->validate(['ext'=>'xlsx,xls'])->move('upload');
            if($info){

                //获取文件路径
                $dir='upload/'.$info->getSaveName();

                //将excel中的数据转化成数组输出
                $datas=$this->excel_to_array($dir,1,1,3);


                $success=0;
                $error=0;
                foreach ($datas as $data){
                    $arr=[];
                    $arr[]='[计科青协]'.$data[0];
                    $arr[]=$data[2];
                    $arr[]="群:364585113";
                    $users[]=$arr;
                    //循环发件
                    $this->sendMessage([$data[1]],$arr);
                }
                return json(['success_num'=>$success,'error_num'=>$error,'result'=>'success']);
            }else{
                return json($info->getError());
            }
        }

    }

}
